package br.com.ravi.deposito.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import br.com.ravi.deposito.dao.GenericDAO;
import br.com.ravi.deposito.dao.HibernateModel;
import br.com.ravi.deposito.exceptions.DAOException;

@WebServlet(urlPatterns="/DaoAction/*")
public class DaoAction extends AbstractAction {
	private static final long serialVersionUID = 1L;
	
	public void loadCollection(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException, ClassNotFoundException, InstantiationException, IllegalAccessException, DAOException {
		String clazz = req.getParameter("clazz");
		if (clazz == null || clazz.length() == 0) {
			return;
		}
		Class<?> forName = Class.forName(clazz);
		@SuppressWarnings("unchecked")
		Class<? extends HibernateModel> validClass = (Class<? extends HibernateModel>)forName;
		HibernateModel model = validClass.newInstance();
		GenericDAO<?> dao = model.getDAO();
		
		if (dao != null) {
			List<?> list = dao.list();
			if (list != null) {
				GsonBuilder builder = new GsonBuilder();
				Gson gson = builder.create();
				String json = gson.toJson(list);
				resp.getWriter().println(json);
			}
		}
	}
}